package HomeService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/HomeReq"
	"gdshop-back-end-go/client-api/app/response/HomeResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/response"
)

func Area(ctx context.Context, parames *HomeReq.Area) *response.JsonResponse {
	if parames.Level > 0 {
		return response.SuccessByRequestMessageData(nil,
			"成功", getAreaLevel(ctx, parames.Level))
	}
	if parames.PCode != "" {
		return response.SuccessByRequestMessageData(nil,
			"成功", getAreaPCode(ctx, parames.PCode))
	}
	return response.SuccessByRequestMessage(nil, "未知类型")
}
func getLevelLen(level int) int {
	var fanhui = 0
	switch level {
	case 4:
		fanhui = 9
		break
	default:
		fanhui = level * 2
		break
	}
	return fanhui
}

// 获取下一级code长度
func getNextCodeLen(pcode string) int {
	var fanhui = 0
	switch len(pcode) {
	case 6:
		fanhui = 9
		break
	case 4:
		fanhui = 6
		break
	case 2:
		fanhui = 4
		break
	default:
		fanhui = 4
		break
	}
	return fanhui
}
func getAreaLevel(ctx context.Context, level int) []*HomeResp.AreaLevel {
	areaLevelList := ([]*HomeResp.AreaLevel)(nil)
	toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "area_plus").Where(
		"LENGTH(code) = ?",
		getLevelLen(level),
	).Order("sort DESC,id ASC").Structs(&areaLevelList)

	return areaLevelList
}
func getAreaLevelResponse(ctx context.Context, level int) *response.JsonResponse {
	areaLevelList := ([]*HomeResp.AreaLevel)(nil)
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "area_plus").Where(
		"LENGTH(code) = ?",
		getLevelLen(level),
	).Order("sort DESC,id ASC").Structs(&areaLevelList)

	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessageData(nil, "成功", areaLevelList)
}
func getAreaPCode(ctx context.Context, pcode string) []*HomeResp.AreaLevel {
	areaLevelList := ([]*HomeResp.AreaLevel)(nil)
	toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "area_plus").Where(
		"code LIKE ? AND LENGTH(code) = ?",
		pcode+"%",
		getNextCodeLen(pcode),
	).Order("sort DESC,id ASC").Structs(&areaLevelList)

	return areaLevelList
}
func getAreaPCodeResponse(ctx context.Context, pcode string) *response.JsonResponse {
	areaLevelList := ([]*HomeResp.AreaLevel)(nil)
	err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "area_plus").Where(
		"code LIKE ? AND LENGTH(code) = ?",
		pcode+"%",
		getNextCodeLen(pcode),
	).Order("sort DESC,id ASC").Structs(&areaLevelList)

	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	return response.SuccessByRequestMessageData(nil, "成功", areaLevelList)
}
